<template>
  <el-drawer v-model="drawer" :title="title" size="60%" @close="onClose">
    <div class="detail-container">
      <el-card class="common-card detail-header">
        <el-divider><span>客户基本信息</span></el-divider>
        <el-descriptions :column="4" border label-class-name="label-style" style="margin-top: 15px">
          <el-descriptions-item label="客户名称">{{ customer.customerName }}</el-descriptions-item>
          <el-descriptions-item label="客户类型">{{ customer.customerType }}</el-descriptions-item>
          <el-descriptions-item label="所属行业">{{ customer.industry }}</el-descriptions-item>
          <el-descriptions-item label="客户分层">{{ customer.segmentName || '未分类' }}</el-descriptions-item>

          <el-descriptions-item label="省份">{{ customer.province }}</el-descriptions-item>
          <el-descriptions-item label="城市">{{ customer.city }}</el-descriptions-item>
          <el-descriptions-item label="区县">{{ customer.district }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ customer.address }}</el-descriptions-item>

          <el-descriptions-item label="负责人">{{ customer.customerHead }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ customer.phone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ customer.email }}</el-descriptions-item>
          <el-descriptions-item label="官网网址">{{ customer.website || '无' }}</el-descriptions-item>
          
          <el-descriptions-item label="来源渠道">{{ getChannelName(customer.customerFrom) }}</el-descriptions-item>
          <el-descriptions-item label="来源商户">{{ getMerchantName(customer.merchantCode) }}</el-descriptions-item>
          <el-descriptions-item label="最近购买时间">{{ customer.lastPurchaseTime || '无' }}</el-descriptions-item>
          <el-descriptions-item label="累计消费金额">{{ customer.totalSpending || 0 }} 元</el-descriptions-item>
          
          <el-descriptions-item label="服务满意度">
            <el-rate v-model="customer.serviceSatisfaction" disabled/>
          </el-descriptions-item>
          <el-descriptions-item label="婚姻状况">{{ customer.maritalStatus || '无' }}</el-descriptions-item>
          <el-descriptions-item label="教育程度">{{ customer.education || '无' }}</el-descriptions-item>
          <el-descriptions-item label="住房类型">{{ customer.housingType || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider><span>公司信息</span></el-divider>
        <el-descriptions :column="4" border label-class-name="label-style" style="margin-top: 15px">
          <el-descriptions-item label="公司名称">{{ customer.companyName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="公司省份">{{ customer.companyProvince || '无' }}</el-descriptions-item>
          <el-descriptions-item label="公司城市">{{ customer.companyCity || '无' }}</el-descriptions-item>
          <el-descriptions-item label="公司区县">{{ customer.companyDistrict || '无' }}</el-descriptions-item>
          
          <el-descriptions-item label="公司地址">{{ customer.companyAddress || '无' }}</el-descriptions-item>
          <el-descriptions-item label="公司电话">{{ customer.companyTel || '无' }}</el-descriptions-item>
          <el-descriptions-item label="公司性质">{{ customer.companyNature || '无' }}</el-descriptions-item>
          <el-descriptions-item label="公司行业">{{ customer.companyIndustry || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider><span>证件信息</span></el-divider>
        <!-- 个人客户显示身份证信息 -->
        <div v-if="customer.customerType === '个人'">
          <el-descriptions :column="4" border label-class-name="label-style" style="margin-top: 15px">
            <el-descriptions-item label="身份证姓名">{{ customer.idCardName || '无' }}</el-descriptions-item>
            <el-descriptions-item label="身份证性别">{{ customer.idCardGender || '无' }}</el-descriptions-item>
            <el-descriptions-item label="身份证民族">{{ customer.idCardNation || '无' }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ customer.identifier || '无' }}</el-descriptions-item>
            
            <el-descriptions-item label="身份证签发机关">{{ customer.idCardIssueAuthority || '无' }}</el-descriptions-item>
            <el-descriptions-item label="身份证有效期">{{ customer.idCardValidDate || '无' }}</el-descriptions-item>
            
            <el-descriptions-item label="身份证地址" :span="4">{{ customer.idCardAddress || '无' }}</el-descriptions-item>
          </el-descriptions>
          
          <el-row :gutter="20" style="margin-top: 15px">
            <el-col :span="8">
              <div class="image-container">
                <div class="image-label">身份证人像面</div>
                <el-image 
                  v-if="customer.idCardFrontImage" 
                  :src="customer.idCardFrontImage" 
                  class="id-card-image"
                  fit="cover"
                  :preview-src-list="[customer.idCardFrontImage]"
                  preview-teleported>
                </el-image>
                <div v-else class="no-image">无图片</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="image-container">
                <div class="image-label">身份证国徽面</div>
                <el-image 
                  v-if="customer.idCardBackImage" 
                  :src="customer.idCardBackImage" 
                  class="id-card-image"
                  fit="cover"
                  :preview-src-list="[customer.idCardBackImage]"
                  preview-teleported>
                </el-image>
                <div v-else class="no-image">无图片</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="image-container">
                <div class="image-label">人脸识别图片</div>
                <el-image 
                  v-if="customer.faceImage" 
                  :src="customer.faceImage" 
                  class="face-image"
                  fit="cover"
                  :preview-src-list="[customer.faceImage]"
                  preview-teleported>
                </el-image>
                <div v-else class="no-image">无图片</div>
              </div>
            </el-col>
          </el-row>
          
          <el-divider><span>人脸识别信息</span></el-divider>
          <el-descriptions :column="4" border label-class-name="label-style" style="margin-top: 15px">
            <el-descriptions-item label="人脸识别结果">{{ customer.faceStatus || '无' }}</el-descriptions-item>
            <el-descriptions-item label="人脸识别得分">{{ customer.faceScore || '无' }}</el-descriptions-item>
            <el-descriptions-item label="人脸识别时间">{{ customer.faceTime || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 企业客户显示营业执照信息 -->
        <div v-else-if="customer.customerType === '企业'">
          <el-descriptions :column="4" border label-class-name="label-style" style="margin-top: 15px">
            <el-descriptions-item label="企业名称">{{ customer.businessLicenseName || '无' }}</el-descriptions-item>
            <el-descriptions-item label="统一社会信用代码">{{ customer.businessLicenseCreditCode || '无' }}</el-descriptions-item>
            <el-descriptions-item label="法人">{{ customer.businessLicenseLegalPerson || '无' }}</el-descriptions-item>
            <el-descriptions-item label="注册资本">{{ customer.businessLicenseRegCapital || '无' }}</el-descriptions-item>
            
            <el-descriptions-item label="成立日期">{{ customer.businessLicenseEstablishDate || '无' }}</el-descriptions-item>
            <el-descriptions-item label="营业期限">{{ customer.businessLicenseValidPeriod || '无' }}</el-descriptions-item>
            <el-descriptions-item label="住所">{{ customer.businessLicenseAddress || '无' }}</el-descriptions-item>
          </el-descriptions>
          
          <div class="image-container" style="margin-top: 15px">
            <div class="image-label">营业执照</div>
            <el-image 
              v-if="customer.businessLicenseImage" 
              :src="customer.businessLicenseImage" 
              class="business-license-image"
              fit="cover"
              :preview-src-list="[customer.businessLicenseImage]"
              preview-teleported>
            </el-image>
            <div v-else class="no-image">无图片</div>
          </div>
        </div>
        
        <el-divider><span>开票信息</span></el-divider>
        <el-collapse v-model="activeCollapseNames">
          <el-collapse-item name="taxInfo">
            <template #title>
              <span>点击展开开票信息</span>
            </template>
            <el-descriptions :column="3" border label-class-name="label-style" style="margin-top: 15px">
              <el-descriptions-item label="纳税人识别号">{{ customer.taxNumber || '无' }}</el-descriptions-item>
              <el-descriptions-item label="账户名称">{{ customer.taxBankAccount || '无' }}</el-descriptions-item>
              <el-descriptions-item label="开户银行">{{ customer.taxBank || '无' }}</el-descriptions-item>
              
              <el-descriptions-item label="银行账户">{{ customer.taxBankAccountNumber || '无' }}</el-descriptions-item>
              <el-descriptions-item label="税务联系人">{{ customer.taxContact || '无' }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>
        
        <el-divider><span>备注</span></el-divider>
        <el-collapse v-model="activeCollapseNames">
          <el-collapse-item name="content">
            <template #title>
              <span>点击展开备注信息</span>
            </template>
            <el-descriptions :column="1" border label-class-name="label-style" style="margin-top: 15px">
              <el-descriptions-item label="备注">
                <editor v-model="customer.content" :height="150" :disabled="true" />
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>
      </el-card>

      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="联系人" name="contact"></el-tab-pane>
        <el-tab-pane label="合同" name="contract"></el-tab-pane>
      </el-tabs>

      <el-card v-if="activeTab==='contact'" class="common-card">
        <div class="btn-form">
          <el-button type="primary" @click="handleContactAdd">新增联系人</el-button>
        </div>
        <el-table :data="contacts" border style="width: 100%">
          <el-table-column prop="contactName" label="姓名" align="center"></el-table-column>
          <el-table-column prop="gender" label="性别" align="center"></el-table-column>
          <el-table-column prop="jobTitle" label="职位" align="center"></el-table-column>
          <el-table-column prop="phone" label="联系电话" align="center"></el-table-column>
          <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button link icon="Edit" @click="editContact(scope.row)"></el-button>
              <el-button link icon="Delete" type="danger" @click="handleContactDelete(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="contactTotal > 0"
            :total="contactTotal"
            v-model:page="contactQuery.pageNumber"
            v-model:limit="contactQuery.pageSize"
            :page-sizes="contactQuery.pageSizeOptions"
            @pagination="getContacts"
        />
      </el-card>
      <el-card v-if="activeTab==='contract'" class="common-card">
        <el-table :data="contracts" border style="width: 100%">
          <el-table-column prop="code" label="合同编码" header-align="center" min-width="50"></el-table-column>
          <el-table-column prop="contractName" label="合同名称" header-align="center" min-width="50">
            <template #default="scope">
              <el-button link type="primary" @click="handleContractDetail(scope.row)">{{ scope.row.contractName }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="合同金额" align="center"></el-table-column>
          <!--<el-table-column prop="currency" label="货币类型" align="center"></el-table-column>
          <el-table-column prop="taxRate" label="税率" align="center"></el-table-column>-->
          <el-table-column prop="signingDate" label="签订日期"  align="center" header-align="center" width="100"></el-table-column>
          <!--<el-table-column prop="effectiveDate" label="生效日期"  align="center"  header-align="center" width="100"></el-table-column>-->
          <el-table-column prop="expirationDate" label="到期日期"  align="center" header-align="center" width="100"></el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="120">
            <template #default="scope">
              <el-tag :type="getStatusLabel(scope.row.status).type">
                {{ getStatusLabel(scope.row.status).label }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="回款" align="center" width="120">
            <template #default="scope">
              <el-button link icon="CreditCard" @click="viewPayment(scope.row)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="contractTotal > 0"
            :total="contractTotal"
            v-model:page="contractQuery.pageNumber"
            v-model:limit="contractQuery.pageSize"
            :page-sizes="contractQuery.pageSizeOptions"
            @pagination="getContracts"
        />
      </el-card>
    </div>
    
    <template #footer>
      <el-button @click="onClose">{{ $t('jbx.text.close') }}</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import modal from '@/plugins/modal'
import { getCustomerOne } from '@/api/customer/customer'
import { listCustomerContact } from '@/api/customer/people'
import { listContract } from '@/api/customer/contract'
import { listMerchant } from '@/api/merchant/merchant'
import { parseTime } from '@/utils/Jinbooks'
import Editor from '@/components/Editor/index.vue'

const { t } = useI18n()
const drawer = ref(false)
const customer = ref({})
const activeTab = ref('contact')
const contacts = ref([])
const contactTotal = ref(0)
const contracts = ref([])
const contractTotal = ref(0)
const merchants = ref([]) // 存储商户列表
const activeCollapseNames = ref([]) // 控制折叠面板的展开状态

const props = defineProps<{
  title?: string
  open?: boolean
  customerId?: string
}>()

const emit = defineEmits(['update:open'])

// 联系人分页查询参数
const contactQuery = ref({
  pageNumber: 1,
  pageSize: 10,
  pageSizeOptions: [10, 20, 50],
  customerId: ''
})

// 合同分页查询参数
const contractQuery = ref({
  pageNumber: 1,
  pageSize: 10,
  pageSizeOptions: [10, 20, 50],
  customerId: ''
})

// 状态标签映射
const getStatusLabel = (status: number) => {
  const statusMap: Record<number, { type: string; label: string }> = {
    1: { type: '', label: '待生效' },
    2: { type: 'warning', label: '生效中' },
    3: { type: 'success', label: '已完成' },
    4: { type: 'info', label: '已终止' },
    5: { type: 'danger', label: '已过期' }
  }
  return statusMap[status] || { type: 'info', label: '未知' }
}

// 获取商户列表
function getMerchants() {
  listMerchant({}).then((res: any) => {
    merchants.value = res.data.records || res.data
  }).catch(() => {
    // 使用默认数据
    merchants.value = [
      { id: "1", merchantName: "自平台", merchantCode: "SELF" },
      { id: "2", merchantName: "示例商户2", merchantCode: "MERCHANT_2" }
    ]
  })
}

// 根据商户编码获取商户名称
function getMerchantName(merchantCode: string) {
  if (!merchantCode) return ''
  const merchant = merchants.value.find((item: any) => item.merchantCode === merchantCode)
  return merchant ? merchant.merchantName : merchantCode
}

// 根据渠道编码获取渠道名称（这里暂时直接显示编码，实际应通过接口获取渠道数据）
function getChannelName(channelCode: string) {
  // TODO: 实际应通过接口获取渠道数据
  return channelCode || ''
}

watch(
    () => props.open,
    async (val) => {
      if (val) {
        drawer.value = val
        // 获取商户列表
        getMerchants()
        
        // 默认折叠开票信息和备注信息
        activeCollapseNames.value = []
        
        if (props.customerId) {
          // 获取客户详情
          const res: any = await getCustomerOne(props.customerId)
          customer.value = res.data
          
          // 设置联系人和合同查询的客户ID
          contactQuery.value.customerId = props.customerId
          contractQuery.value.customerId = props.customerId
          
          // 获取联系人和合同数据
          getContacts()
          getContracts()
        }
      } else {
        drawer.value = false
      }
    },
    { immediate: true }
)

// 获取联系人列表
function getContacts() {
  listCustomerContact(contactQuery.value).then((res: any) => {
    contacts.value = res.data.records
    contactTotal.value = res.data.total
  })
}

// 获取合同列表
function getContracts() {
  listContract(contractQuery.value).then((res: any) => {
    contracts.value = res.data.records
    contractTotal.value = res.data.total
  })
}

function onClose() {
  drawer.value = false
  emit('update:open', false)
}

// 新增联系人
function handleContactAdd() {
  // TODO: 实现新增联系人逻辑
}

// 编辑联系人
function editContact(row: any) {
  // TODO: 实现编辑联系人逻辑
}

// 删除联系人
function handleContactDelete(row: any) {
  // TODO: 实现删除联系人逻辑
}

// 查看合同详情
function handleContractDetail(row: any) {
  // TODO: 实现查看合同详情逻辑
}

// 查看回款
function viewPayment(row: any) {
  // TODO: 实现查看回款逻辑
}
</script>

<style scoped>
.detail-container {
  padding: 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.detail-header {
  margin-bottom: 20px;
}

.label-style {
  width: 120px;
}

.image-container {
  text-align: center;
  margin-bottom: 15px;
}

.image-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.id-card-image {
  width: 100%;
  height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.business-license-image {
  width: 100%;
  height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.face-image {
  width: 100%;
  height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.no-image {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  color: #909399;
}

:deep(.el-descriptions__label) {
  width: 120px !important;
}
</style>